package learning.groovy.collection

class ListDemo {
	static main(args){
		def myList = [1, 2, 3]
		println 'myList:' + myList
		println 'myList size:' + myList.size()
		println myList instanceof ArrayList

		def emptyList = []
		println 'emptyList size:' + emptyList.size()

		def longList = (0..1000).toList()
		println 'longList[555]:' + longList[555]

		List explicitList = new ArrayList()
		explicitList.addAll(myList)
		println 'explicitList:' + explicitList
		println 'explicitList size:' + explicitList.size()

		explicitList = new LinkedList(myList)
		println 'explicitList:' + explicitList
		println 'explicitList size:' + explicitList.size()

		myList = ['a', 'b', 'c', 'd', 'e', 'f']
		println myList[0..2]
		println myList[0, 2, 4]

		myList[0..2] = ['x', 'y', 'z']
		println myList

		//Removing elements
		//当指定的列表值小于给定的范围或者是空的时候，这个列表被收缩
		myList[3..5] = []
		println myList

		//Adding elements
		//当指定的列表值更大时，列表进行增长
		myList[1..1] = ['y', '1', '2']
		println myList
		//[x, y, 1, 2, z]

		println myList[0]
		println myList[-1]
		println myList[-3..-1]
		println myList[1..-2]
		println myList[4..0]

		myList = []
		myList += 'a'
		println myList
		//['a']
		myList += ['b', 'c']
		println myList
		//['a', 'b', 'c']

		myList = []
		myList << 'a' << 'b'
		println myList
		//['a', 'b']
		println myList - ['b']
		//['a']
		println myList * 2
		//['a', 'b', 'a', 'b']

		myList = ['a', 'b', 'c']
		println myList.isCase('a')
		def candidate = 'a'
		switch(candidate){
			case myList : println "myList contains 'a'"; break
			default : println 'default'
		}

		println (['x', 'a', 'z'].grep(myList))
		//['a']

		def log = ''
		for(i in [1, 'x', 5]){
			log += i
		}
		println log
		//1x5

		def list = [1, 2, 3]
		def popped = list.pop() //堆栈(stack)
		println popped
		println list
		//[1, 2]
		
		list = list.reverse()
		println list
		//[2, 1]
		
		list = [[1, 0], [0, 1, 2]]
		println list.sort{ a,b ->
			a[0] <=> b[0]
		}
		//[[0, 1, 2], [1, 0]]
		println list.sort{ item ->
			item.size()
		}
		//[[1, 0], [0, 1, 2]]
		
		def doubled = [1, 2, 3].collect{ item -> item*2 }
		println doubled
		//[2, 4, 6]
		
		def odd = [1, 2, 3].findAll{ item -> item%2 == 1 }
		println odd
		//[1, 3]
		
	}
}
